/*
 * Description: 接口状态中心
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Dongxu.Ni
 * Date: 2020/3/10 15:20
 */

import { apiList } from '../../api/sys/api'
import { getLangMappingProperty } from '../../lang/lang-set'

const state = {
  // 全局接口集合数据
  apiCollects: []
}
const getters = {
  getApiCollects: state => state.apiCollects,
  getApiNameByPath: state => apiPath => {
    const api = state.apiCollects.find(api => api.apiPath === apiPath)
    return api ? api.apiName : apiPath
  }
}

const mutations = {
  SET_API: (state, apiCollects) => {
    state.apiCollects = apiCollects
  },
  REMOVE_API: state => {
    state.apiCollects = []
  },
  SET_API_WITH_LANGUAGE: (state, language) => {
    const langMappingProperty = getLangMappingProperty(language, 'apiName')
    for (let i = 0, len = state.apiCollects.length; i < len; i++) {
      state.apiCollects[i].apiName = state.apiCollects[i][langMappingProperty]
    }
  }
}

const actions = {
  initApiCollects({ commit, rootState }) {
    const language = rootState.language.language
    const langMappingProperty = getLangMappingProperty(language, 'apiName')
    return new Promise((resolve, reject) => {
      apiList()
        .then(response => {
          const apiList = response.data
          for (let i = 0, len = apiList.length; i < len; i++) {
            apiList[i].apiName = apiList[i][langMappingProperty]
          }
          commit('SET_API', apiList)
          resolve()
        })
        .catch(err => reject(err))
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
